
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class CommonUtils{

  static getLocalPath() async {
    Directory appDir;
    if (Platform.isIOS) {
      appDir = await getApplicationDocumentsDirectory();
    } else {
      appDir = await getTemporaryDirectory();
    }
    PermissionStatus permission = await Permission.storage.request();

    if (permission != PermissionStatus.granted) {
      showToast('没有权限');return;
    }
    String appDocPath = appDir.path + "/djb";
    Directory appPath = Directory(appDocPath);
    bool exist = await appPath.exists();
    if(!exist){
      await appPath.create(recursive: true);
    }
    return appPath;
  }


  static saveImage(String url) async {
    Future<String> _findPath(String imageUrl) async {
      final cache = await DefaultCacheManager();//.getInstance();
      final file = await cache.getSingleFile(imageUrl);
      if (file == null) {
        return null;
      }
      Directory localPath = await CommonUtils.getLocalPath();
      if (localPath == null) {
        return null;
      }
      final name = splitFileNameByPath(file.path);
      final result = await file.copy(localPath.path + name);
      return result.path;
    }
    return _findPath(url);
  }

  static splitFileNameByPath(String path) {
    return path.substring(path.lastIndexOf("/"));
  }


  static copy(String data, BuildContext context) {
    Clipboard.setData(new ClipboardData(text: data));
    showToast('复制成功');
  }

  static void showToast(String content,
      {Toast length = Toast.LENGTH_SHORT,
        ToastGravity gravity = ToastGravity.BOTTOM,
        Color backColor = Colors.black54,
        Color textColor = Colors.white}) {
    if (content != null) {
      if (content != null && content.isNotEmpty) {
        Fluttertoast.showToast(
            msg: content,
            fontSize: 13.0);
      }
    }
  }
}